﻿using System;
using System.ComponentModel.DataAnnotations;
using Fuse8.GlobalizationFramework.BusinessServices;

namespace Fuse8.GlobalizationFramework.MvcPowered.Attributes
{
    /// <summary>
    /// Specifies that data is required
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class LocalizedRequiredAttribute : RequiredAttribute
    {
        private const string MessagePatternResource = "error-pattern-required";

        private readonly string messagePattern;

        /// <summary>
        /// Initializes attribute with default error message
        /// </summary>
        public LocalizedRequiredAttribute()
        {
            messagePattern = ResourceService.FindValue(MessagePatternResource, "{0} is required.");
        }

        /// <summary>
        /// Initializes attribute by resource key
        /// </summary>
        /// <param name="resourceKey">Resource key</param>
        public LocalizedRequiredAttribute(string resourceKey)
            : base()
        {
            ErrorMessage = ResourceService.FindValue(resourceKey);
        }

        /// <summary>
        /// Initializes attribute by resource key and default value
        /// </summary>
        /// <param name="resourceKey">Resource key</param>
        /// <param name="defaultMessage">Defualt value</param>
        public LocalizedRequiredAttribute(string resourceKey, string defaultMessage)
            : base()
        {
            ErrorMessage = ResourceService.FindValue(resourceKey, defaultMessage);
        }


        /// <summary>
        /// Formats error message
        /// </summary>
        /// <param name="name">Property name</param>
        /// <returns></returns>
        public override string FormatErrorMessage(string name)
        {
            return string.IsNullOrEmpty(ErrorMessage) ? string.Format(messagePattern, name) : ErrorMessage;
        }
    }
}